package org.example;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OrderedFileWriter {
    private final Lock lock = new ReentrantLock();
    private final Condition canWrite = lock.newCondition();
    private int currentSequence = 1;
    private final String fileName;

    public OrderedFileWriter(String fileName) {
        this.fileName = fileName;
    }

    public void setCurrentSequence(int currentSequence) {
        this.currentSequence = currentSequence;
    }

    public void write(int threadId, String content, String title) throws InterruptedException, IOException {
        lock.lock();
        try {
            // 等待当前线程的顺序
            while (currentSequence != threadId) {
                canWrite.await();
            }
            System.out.println("开始写入:" + title);
            // 写入数据
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true))) {
                bw.write("\n" + title + "\r\n");
                bw.write(content);
                bw.newLine();
            }
            // 更新顺序并通知下一个线程
            currentSequence++;
            canWrite.signalAll();
        } finally {
            lock.unlock();
        }
    }
}